import BrowserService from '../../browser.service';
import { LoginConfig } from '../../config';
import { consoleLog, delay } from '../../utils';
const { title, pageUrl, from, screenshotName} = LoginConfig;
export default class LoginController extends BrowserService {
  constructor() {
    super();
  }
  async init() {
    await this.login();
  }
  async login() {
    await this.exportConfig(title, from);
    await this.page.goto(pageUrl, { waitUntil: 'networkidle' });
    await this.submitForm(from);
    const fromDataState = await this.expectFormData(from);
    if (fromDataState) {
      await this.expectLogin();
    }
  }
  async expectLogin() {
    const { testPage } = LoginConfig;
    const isVisible = await this.page.isVisible('.thy-alert-content span');
    if (isVisible) {
      const errText = await this.page.innerText('.thy-alert-content span');
      console.log(errText);
      await consoleLog(`登录测试 ${errText}`, this.logPath);
    } else {
      if (this.page.url() !== testPage.pageUrl) {
        await this.page.goto(testPage.pageUrl, {
          waitUntil: 'networkidle',
        });
      }
      await delay(1000);
      await this.clickGroup(testPage.btnGroup);
      await this.expectTestResult(testPage.result);
    }
    await this.screenshot(screenshotName);
  }
  /**
   * 检查登录状态
   * @returns
   */
  async checkLogin(): Promise<boolean> {
    // 查看当前是不是登录页面
    const isLoginStart = await this.page.isVisible('app-signin-page');
    return !isLoginStart;
  }
  async autoLogin() {
    const loginStart = await this.checkLogin();
    if (loginStart) {
      console.log('登陆成功');
    } else {
      await this.login();
    }
  }
}

/**
 * 登录测试步骤
 * 1. 访问登录页面['networkidle'- 当至少500ms没有网络连接时，认为操作完成。]
 * 2. 输入用户名   --------|
 * 3. 输入密码    ---------| --- 合并为表单提交
 * 4. 点击登录按钮 --------|
 * 5. 验证登录状态[根据错误信息是否正确来验证]
 * 6. 正确的话访问帐号设置页面进行二次验证比对
 * 7. 登录操作测试完毕，储存屏幕快照
 */
